<!--
 * @Description: 本地文件附件上传
 * @Author: zhailei
 * @Date: 2021-06-02 13:38:08
 * @LastEditTime: 2023-06-16 11:36:09
 * @LastEditors: your name
 * @FilePath: \vite-demoe:\wwwroot\Vue\\-cloud-vue\src\components\TopVUI\accessory\index.vue
-->
<template>
  <a-card :bordered="false" :bodyStyle="{ padding: 0 }">
    <!-- 操作按钮 -->
    <tool-bar
      v-if="btnType"
      @search="$refs.table.refresh(true)"
      @reset="
        () => {
          (this.queryParam = {}), $refs.table.refresh(true);
        }
      "
    >
      <template slot="toolBtn" slot-scope="scope">
        <a-button
          class="cu-btn-primary"
          v-if="!type || type != 1"
          @click="handleaddArchivePost"
          icon="upload"
        >
          {{ $ct("upload", "上传") }}</a-button
        >
        <a-button
          class="cu-btn-danger"
          v-if="(tag && tag != 'fdsFile' && !type) || type != 1"
          icon="delete"
          @click="handleSub($refs.table.selectedRowKeys)"
          >{{ $ct("delete", "删除") }}</a-button
        >
      </template>
    </tool-bar>
    <DataGrid
      ref="table"
      :columns="columns"
      :url="url"
      :queryParam="queryParam"
      rowKey="uuid"
      :format-conditions="true"
    >
      <template
        v-for="col in ['renderFileName']"
        :slot="col"
        slot-scope="{ text, record }"
      >
        <div>
          <a-input
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="(e) => handleChange(e.target.value, record.uuid, col)"
          />
          <template v-else>
            <t-ellipsis :value="text">
              <template slot="content">
                <icon-fonts
                  :icon="getIconFontByFile(text)"
                  style="margin-right: 5px;"
                />
                <a @click="handleDownLoad(record)">{{ text | ellipsis(30) }}</a>
              </template>
            </t-ellipsis>
          </template>
        </div>
      </template>
      <template slot="renderAction" slot-scope="{ text, record }">
        <div class="editable-row-operations">
          <a @click="handleDownLoad(record)">{{ $ct("download", "下载") }}</a>
          <span v-if="showPreview(record)" class="action-margin"></span>
          <a v-if="showPreview(record)" @click="handlePreview(record)">{{
            $ct("preview", "预览")
          }}</a>
          <template v-if="type && type != 1">
            <span class="action-margin"></span>
            <a
              v-if="tag && tag === 'fdsFile'"
              class="action-delete"
              @click="handleSub(record, { fileUrl: record.url })"
              >{{ $ct("delete", "删除") }}</a
            >
            <a v-else @click="handleSub(record)" class="action-delete">{{
              $ct("delete", "删除")
            }}</a>
          </template>
        </div>
      </template>
    </DataGrid>
    <!--	新增编辑	 -->
    <t-modal
      title="图片预览"
      :width="800"
      :visible="imgVisible"
      @ok="() => (imgVisible = false)"
      @cancel="() => (imgVisible = false)"
    >
      <div style="width: 100%;">
        <img style="width: 100%;object-fit: center;" :src="imgPreview" />
      </div>
    </t-modal>

    <!-- 文件预览 -->
    <previewModal
      :visible.sync="previewVisible"
      :loading="previewLoading"
      ref="previewModal"
    ></previewModal>
    <!-- 文件预览 -->

    <!-- 上传文件 -->
    <web-upload
      ref="createPostModal"
      :visible="visible"
      :url="url.webUpload"
      :loading="confirmLoading"
      :data="mdl"
      @cancel="
        () => {
          visible = false;
        }
      "
      @ok="handleOkUserPost"
      @resTable="resTable"
    />
  </a-card>
</template>

<script>
import { mapGetters } from "vuex";
import previewModal from "@/pages/document/minio/previewModal"; //预览
import { getToken } from "@/utils/TopVUI";
import "@/utils/filter";
import { DataGrid } from "@/components";
import { dataGridMixin } from "@/mixins/dataGridMixin";
import { baseUrl } from "@/services/baseUrl.js";
import Vue from "vue";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { pdfStreamHandeler } from "@/services/common";
import webUpload from "@/components/TopVUI/custom/webupload.vue";
import { getIconFont, getTypeByList, fileSuffix } from "@/utils/util";
import { download, downloadDfs } from "@/utils/TopVUI.js";
import store from "@/store";

import { downloadMinio } from "@/utils/TopVUI";

export default {
  name: "Table",
  components: {
    DataGrid,
    webUpload,
    previewModal,
  },
  mixins: [dataGridMixin],
  props: {
    paramList: {
      type: Object,
    },
    url: {
      type: Object,
      default: () => {
        return {
          webUpload: "/document/fdfs/uploadfile", //上传
          getPageSet: "/document/fastdfs/getPageSet", //获取分页
          deleteBatch: "/document/fdfs/deleteFile", //删除
          update: "/system/attachment/update", //更新
        };
      },
    },
    type: {
      type: Number,
      default: 2,
    },
    tag: {
      type: String, //fdsFile   区别删除是否带参数
      default: "default",
    },
    label: {
      //文字说明
      type: String,
      default: "attachment",
    },
    btnType: {
      //是否显示操作按钮
      type: Boolean,
      default: true,
    },
    fileType: {
      //文件上传
      type: String,
      default: "oss",
    },
    bucket: {
      // 上传桶名mdl新增属性
      type: String,
      default: "",
    },
  },
  data() {
    return {
      columns: [
        {
          title: "文件名称",
          dataIndex: "fileName",
          width: 300,
          scopedSlots: {
            customRender: "renderFileName",
          },
          ellipsis: true,
        },
        {
          title: "文件大小",
          dataIndex: "fileSize",
          width: 100,
          langCode: "sizeText",
          // sorter: true,
        },
        {
          title: "上传人",
          width: 100,
          dataIndex: "creator",
          langCode: "createdBy",
          ellipsis: true,
        },
        {
          title: "上传时间",
          width: 100,
          dataIndex: "createTime",
          langCode: "Creation time",
          sorter: true,
        },
        {
          title: "操作",
          width: 150,
          fixed: "right",
          dataIndex: "action",
          scopedSlots: {
            customRender: "renderAction",
          },
        },
      ],
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      queryParam: {
        puuid: 1,
      },
      // url: {
      //   getPageSet: "/system/testDemo/getPageSet",
      //   save: "/system/testDemo/save",
      //   update: "/system/testDemo/update",
      //   deleteBatch: "/system/testDemo/deleteBatch",
      // },
      action: "",
      headers: {
        token: Vue.ls.get(ACCESS_TOKEN),
      },
      imgVisible: false,
      imgPreview: "",
      urlpdf: {
        pdfStreamHandeler: "/system/attachment/pdfStreamHandeler",
      },
      previewLoading: false,
      previewVisible: false,
    };
  },
  computed: {
    ...mapGetters(["configData"]),
  },
  created() {
    this.action = baseUrl + this.url;
    this.headers.token = Vue.ls.get(ACCESS_TOKEN);
  },
  methods: {
    getIconFontByFile(val) {
      return getIconFont(val);
    },
    // 判断是否显示在线编辑按钮
    showTypePreview(e) {
      // const typeList = ['.doc', '.ppt', '.xls','.pdf']
      return getTypeByList(fileSuffix, e.filePath);
    },
    // 刷新
    refreshList(e) {
      this.uuid = "";
      this.rows = "";
      this.selectedRowKeys = [];
      this.queryParam = e ? e : {};
      this.editingKey = "";
      this.dataSource = [];
      this.$refs.table.refresh();
    },
    resTable() {
      this.visible = false;
      this.$message.info("添加成功");
      this.editingKey = "";
      this.dataSource = [];
      this.$refs.table.refresh();
    },
    handleaddArchivePost() {
      if (this.queryParam.puuid) {
        if (this.queryParam.puuid === "null") {
          this.$message.warn("此合同未生效");
          return false;
        }
        if (this.queryParam.puuid == "1") {
          this.$message.info("请先选择需要操作的数据");
        } else {
          this.mdl = {
            puuid: this.queryParam.puuid,
          };
          if (this.bucket) {
            this.mdl.bucket = this.bucket;
          }
          this.visible = true;
        }
      } else {
        this.$message.info("请先选择需要操作的数据！");
      }
      this.editingKey = "";
      const form = this.$refs.createPostModal.form;
      form.resetFields(); // 清理表单数据（可不做）
      this.$refs.createPostModal.add(this.mdl);
    },

    handleOkUserPost() {
      const formUserPost = this.$refs.createPostModal.form;
      this.visible = false;
      this.confirmLoading = false;
      formUserPost.resetFields();
      this.dataSource = [];
      this.$refs.table.refresh();
    },
    // 下载
    handleDownLoad(e) {
      if (this.label === "attachment") {
        download(e.uuid);
      } else {
        //downloadDfs(e.url, e.fileName);
        let bucket = this.label == "随意值" ? "yx-cloud-vue" : "vue-accessory";
        downloadMinio(bucket, e.fileName);
      }
    },

    // 删除
    handleSub(record, paramar) {
      const that = this;
      let uuids = "";
      if (!record || record.length === 0) {
        this.$message.warn("请勾选需要删除的数据", 1.5);
        return;
      } else if (record && record[0]) {
        uuids = record.toString();
      } else {
        uuids = record.uuid;
      }
      let value = {
        uuid: uuids,
        objectName: record.fileName,
        ...paramar,
      };
      if (this.label == "随意值") {
        value.bucket = "yx-cloud-vue";
      }
      that.$confirm({
        title: "警告",
        content: `确定要执行该操作吗?`,
        okText: "删除",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          // 在这里调用删除接口
          that.$post(that.url.deleteBatch, value).then((res) => {
            if (res.statusCode === 200 || res === 1) {
              that.$message.success(res.message, 1.5);
              if (that.fetch) {
                that.fetch(that.queryParam);
              } else {
                that.$refs.table.refresh();
              }
            } else {
              that.$message.error(res.message, 1.5);
            }
          });
        },
        onCancel() {},
      });
    },
    //预览
    showPreview(e) {
      const imgType = [
        "jpg",
        "jpeg",
        "gif",
        "png",
        "pdf",
        "xls",
        "doc",
        "docx",
        "txt",
        "xlsx",
      ];
      return imgType.find((val) => e.fileName.split(".").pop() === val);
    },
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    handlePreview(e) {
      this.$refs.previewModal.fileUrl = "";
      this.$nextTick(() => {
        const medieaType = [".jpg", ".jpeg", ".png", ".gif"];
        const flag = getTypeByList(medieaType, e.fileName);
        if (flag) {
          this.imgVisible = true;
          this.imgPreview =
            baseUrl + "/system/attachment/showPic?path=" + e.filePath;
        } else {
          this.$post("/system/attachment/pdfStreamHandeler", {
            uuid: e.uuid,
          }).then((res) => {
            if (res.statusCode !== 300) {
              var binaryData = [];
              binaryData.push(res);
              const blob = new Blob(binaryData, {
                type: "application/pdf;charset-UTF-8",
              });
              const objectUrl = window.URL.createObjectURL(blob);
              window.open("./statics/pdf/web/viewer.html?file=" + objectUrl);
            } else {
              this.$message.error(res.message ? res.message : "操作失败", 1.5);
            }
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.table {
  background-color: @base-bg-color;
  padding: 24px;
}
</style>
